<template>
  <el-form
    :ref="formRef"
    :model="model"
    :rules="rules"
    v-bind="$attrs"
    size="small"
    label-width="auto"
  >
    <el-form-item
      v-for="(item, index) in config"
      :label="item.label"
      :props="item.props"
      :key="index"
    >
      <component
        :is="item.component"
        v-model="model[item.props]"
        :placeholder="placeholder(item)"
        :readonly="item.readonly || readonly"
      ></component>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  props: {
    // 表单引用名称
    formRef: {
      type: String,
      default: "formRef",
    },
    // 配置项
    config: {
      type: Array,
      required: true,
      default: () => [
        {
          label: "标题",
          props: "title",
          component: "el-input",
          readonly: false,
        },
      ],
    },
    // 表单数据模型
    model: {
      type: Object,
      required: true,
    },
    // 表单规则
    rules: {
      type: Object,
      required: false,
    },
    readonly: {
      type: Boolean,
      default: false,
    },
  },
  computed: {
    /**
     * 根据表单项配置获取占位符
     */
    placeholder() {
      return (item) => {
        if (item.placeholder) return item.placeholder;
        const arr = ["el-input", "el-input-number"];
        return !item.component || arr.includes(item.component)
          ? `请输入${item.label || ""}`
          : `请选择${item.label || ""}`;
      };
    },
  },
  methods: {},
};
</script>

<style lang="scss" scoped></style>
